package com.sky.controller.user;

import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * PROJECT_NAME: sky-take-out
 * NAME: DishController
 *
 * @AUTHOR: zhang
 * DATE: 2023/11/29
 * DESCRIPTION :
 */
@Slf4j
@Api(tags = "C端-菜品信息表现层接口") //@Api:用户描述类的相关信息
@RestController("userDishController")
@RequestMapping("/user/dish")
public class DishController {
    @Resource
    private DishService dishService;
    @Resource
    private RedisTemplate redisTemplate;

    private static final String DISH_CACHE = "DISH_CACHE::";

    @ApiOperation("根据分类id查询菜品信息")
    @GetMapping("/list")
    public Result<List<DishVO>> selectDishByCategoryId(Long categoryId) {
        log.info("【根据分类id查询菜品信息】分类id，{}", categoryId);
        //查询Redis缓存中是否保存了菜品信息
        List<DishVO> dishVOS = (List<DishVO>) redisTemplate.opsForValue().get(DISH_CACHE + categoryId);
        //如果不为空，则直接返回
        if (dishVOS!=null && dishVOS.size() > 0) {
            return Result.success(dishVOS);
        }
        //不存在，则查询数据库，并把返回的数据放到Redis缓存中
        List<DishVO> dishVOList = dishService.selectDishAndFlavoByCategoryId(categoryId);
        redisTemplate.opsForValue().set(DISH_CACHE + categoryId, dishVOList);
        return Result.success(dishVOList);
    }
}
